using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;

namespace RideMe.Core
{
    public static class SerializationService
    {
        /// <summary>
        /// Serializes the object.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="target">The target.</param>
        public static void SerializeObject(string path, object target)
        {
            if (target != null)
            {
                using (Stream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    IFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(stream, target);
                }
            }
        }

        /// <summary>
        /// Deserializes the object.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns></returns>
        public static object DeserializeObject(string path)
        {
            using (Stream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read))
            {
                IFormatter formatter = new BinaryFormatter();

                object deserializedValue = null;
                if (stream.Length != 0)
                {
                    deserializedValue = formatter.Deserialize(stream);
                }

                return deserializedValue;

            }
        }

        public static void SerializeSnippets(string path, List<Snippet> snippets)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Snippet>));
            TextWriter writer = new StreamWriter(path);
            serializer.Serialize(writer, snippets);
            writer.Close();
        }

        public static List<Snippet> DeserializeSnippets(string path)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Snippet>));
            List<Snippet> snippets;
            TextReader reader = new StreamReader(path);
            snippets = (List<Snippet>)serializer.Deserialize(reader);
            reader.Close();

            return snippets;
        }
    }
}
